/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vng.survey.filter;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author namhh
 */
public class RoutingFilter implements Filter {

    private static final Pattern REWRITE_PATTERN = Pattern.compile("/(survey)/(([a-zA-Z0-9]*)/(.*)?(.*))?");

    @Override
    public void init(FilterConfig fc) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse sr1, FilterChain fc) {
        try{
        
        HttpServletRequest request = (HttpServletRequest) req;
        String pathInfo = request.getPathInfo();
        System.out.println(request.getRequestURL().toString());
        System.out.println("pathInfo: " + pathInfo);
        Matcher m = REWRITE_PATTERN.matcher(pathInfo);

        if (m.find()) {
//            if (m.group(2) == null && !"survey".equals(m.group(1))) {
//                RequestDispatcher dispatcher = request.getRequestDispatcher("/" + m.group(1));
//                dispatcher.forward(req, sr1);
//            } else {
                System.out.println(m.groupCount());
                System.out.println(m.group());
                String requestPath = "/" + m.group(4) + "?fanpage=" + m.group(3) + "&" + m.group(5);
                RequestDispatcher dispatcher = request.getRequestDispatcher(requestPath);
                dispatcher.forward(req, sr1);
//            }
        } else {
            fc.doFilter(req, sr1);
        }
        }catch(ServletException | IOException ex){
            try {
                fc.doFilter(req, sr1);
            } catch (    IOException | ServletException ex1) {
                Logger.getLogger(RoutingFilter.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
        
        
    }

    @Override
    public void destroy() {
    }
}
